package com.jason.schedulemigrationtest.service.impl;


import com.jason.schedulemigrationtest.mapper.ExpressOrderHistoryMapper;
import com.jason.schedulemigrationtest.mapper.ExpressOrderMapper;
import com.jason.schedulemigrationtest.po.ExpressOrder;
import com.jason.schedulemigrationtest.service.DataMigrationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Service
public class DataMigrationServiceImpl implements DataMigrationService {

    @Resource
    private ExpressOrderMapper expressOrderMapper;

    @Resource
    private ExpressOrderHistoryMapper expressOrderHistoryMapper;

    public List<Long> queryIdsByCutoff(String cutoff,Long lastId, int pageSize) {
        return  expressOrderMapper.queryOrderIdsByCutoff(cutoff, lastId, pageSize);
    }

    @Transactional
    public int migrateDataByIds(List<Long> OrderIds) {
        int nums = OrderIds.size();
        List<ExpressOrder>  expressOrders = expressOrderMapper.queryByOrderIds(OrderIds);

        int insertNums = expressOrderHistoryMapper.batchInsert(expressOrders);
        int  delNums = expressOrderMapper.deleteByIds(OrderIds);
        log.info("nums:"+nums+"| insertNums:"+insertNums+"| delNums:"+delNums);
        boolean ok = nums ==  insertNums && nums == delNums;

        if(!ok){
            String errMsg = String.format(
                    "应迁移 %d 条数据，实际插入 %d 条数据,实际删除 %d 条数据,抛出异常，进行回滚",
                    nums, insertNums, delNums);
            throw new IllegalStateException(errMsg);
        }

        log.info("迁移完成，共"+insertNums+"条数据插入成功，共"+delNums+"条数据删除成功");
        return nums;

    }
}
